package userDao

import (
	"iristest/common/log"
	"iristest/dao"
	"iristest/do/user"
)

func SelectPasswordByUsername(username string) *user.User {
	u := &user.User{}
	_, err := dao.Xorm.Cols("id", "password", "status").Where("username=?", username).Get(u)
	if err != nil {
		return nil
	}

	if u == nil {
		return nil
	}
	return u
}

func SelectUserInfoByUserId(id int64) *user.UserInfo {
	u := &user.UserInfo{}
	dao.Xorm.Where("user_id=?", id).Get(u)
	return u
}

func InsertUser(u *user.User) int64 {
	_, err := dao.Xorm.Insert(u)
	if err != nil {
		log.Err(err, "注册插入数据时发生错误")
		return 0
	}
	return (*u).Id
}

func InsertUserInfo(u *user.UserInfo) int64 {
	_, err := dao.Xorm.Insert(u)
	if err != nil {
		log.Err(err, "注册插入数据时发生错误")
		return 0
	}
	return (*u).Id
}

func UpdateUserInfoByUserId(u *user.UserInfo) bool {
	rs, err := dao.Xorm.Where("user_id=?", (*u).UserId).Update(u)
	if err != nil {
		log.Err(err, "更新用户信息时数据库时出现错误")
		return false
	}
	return rs != 0
}

func DelUserAndInfoByIdForge(id int64) bool {
	u := &user.User{
		Status: 4,
	}
	rs1, err := dao.Xorm.ID(id).Update(u)
	if err != nil {
		log.Err(err, "伪删除用户时错误")
		return false
	}
	ui := &user.UserInfo{
		Status: 4,
	}
	rs2, err := dao.Xorm.Where("user_id=?", id).Update(ui)
	if err != nil {
		log.Err(err, "伪删除用户信息时错误")
		return false
	}
	return rs1 != 0 || rs2 != 0
}
func DelUserAndInfoById(id int64) bool {
	u := &user.User{
		Id: id,
	}
	rs1, err := dao.Xorm.Delete(u)
	if err != nil {
		log.Err(err, "删除用户信息时错误")
		return false
	}
	ui := &user.UserInfo{
		UserId: id,
	}
	rs2, err := dao.Xorm.Delete(ui)
	if err != nil {
		log.Err(err, "删除用户信息时错误")
		return false
	}
	return rs1 != 0 || rs2 != 0
}
